//
//  UILabel+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/8/3.
//  Copyright © 2021 qindong. All rights reserved.
//

import Foundation
import UIKit

extension UILabel {
    // MARK: - 图片的NSTextAttachment 调用前先设置label的font
    func addAttachWithImage(_ image : UIImage) -> NSTextAttachment {
        let attach : NSTextAttachment = NSTextAttachment()
        attach.image = image
        let mid = font.descender + font.capHeight
        attach.bounds = CGRect(x: 0, y: font.descender - image.height / 2 + mid + 2, width: image.width, height: image.height).integral
        return attach
    }

    // MARK: - view的NSTextAttachment 调用前先设置label的font
    func addAttachWithView(_ view : UIView) -> NSTextAttachment {
        let attach : NSTextAttachment = NSTextAttachment()
        attach.image = .qmui_image(with: view)
        let mid = font.descender + font.capHeight
        attach.bounds = CGRect(x: 0, y: font.descender - view.qmui_height / 2 + mid + 2, width: view.qmui_width, height: view.qmui_height).integral
        return attach
    }
    
    // MARK: - UILabel 便捷构造器
    convenience init(font : UIFont, textColor : UIColor, textAlignment : NSTextAlignment = .left) {
        self.init()
        self.textColor = textColor
        self.font = font
        self.textAlignment = textAlignment
    }
}
